package com.breaking.second.activity.pager.adapter;

import android.content.Context;
import android.content.Intent;
import android.text.format.DateUtils;
import android.view.View;

import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.breaking.second.R;
import com.breaking.second.activity.GoodsDetailActivity;
import com.breaking.second.databinding.ItemBuyGoodsBinding;
import com.breaking.second.entity.BuyGoodsEntity;
import com.breaking.second.utils.compat.RecyclerCompat;
import com.bumptech.glide.Glide;

import java.util.List;

public class BuyGoodsAdapter extends BaseAdapter<ItemBuyGoodsBinding> {
    private final List<BuyGoodsEntity> buyGoodsEntities;

    public BuyGoodsAdapter(Context context, List<BuyGoodsEntity> buyGoodsEntities) {
        super(context);
        this.buyGoodsEntities = buyGoodsEntities;
    }

    @Override
    public void onBindViewHolder(ItemBuyGoodsBinding binding, int position) {
        super.onBindViewHolder(binding, position);

        BuyGoodsEntity buyGoodsEntity = buyGoodsEntities.get(position);

        if (buyGoodsEntity.getImageUrlList() != null) {
            ImageAdapter imageAdapter = new ImageAdapter(getContext(), buyGoodsEntity.getImageUrlList());
            binding.images.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
            binding.images.setAdapter(imageAdapter);
        }
        if (buyGoodsEntity.getSellerAvatar() == null) {
            Glide.with(getContext()).load(buyGoodsEntity.getBuyerAvatar()).placeholder(R.mipmap.ic_launcher).into(binding.sellerAvatar);
        } else {
            Glide.with(getContext()).load(buyGoodsEntity.getSellerAvatar()).placeholder(R.mipmap.ic_launcher).into(binding.sellerAvatar);
        }
        if (buyGoodsEntity.getSellerName() == null) {
            binding.sellerName.setText(buyGoodsEntity.getBuyerName());
        } else {
            binding.sellerName.setText(buyGoodsEntity.getSellerName());
        }
        binding.price.setText(String.valueOf(buyGoodsEntity.getPrice()));
        binding.content.setText(buyGoodsEntity.getGoodsDescription());
        RecyclerCompat.SpacesItemDecoration(binding.images);

        binding.addr.setText(String.format("%s", DateUtils.getRelativeTimeSpanString(Long.parseLong(buyGoodsEntity.getCreateTime())).toString()));
        binding.getRoot().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), GoodsDetailActivity.class);
                intent.putExtra("id", String.valueOf(buyGoodsEntity.getGoodsId()));
                getContext().startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return buyGoodsEntities.size();
    }
}
